package com.taptech.doufu.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taptech.doufu.R;
import com.taptech.doufu.event.EventBusRefreshData;
import com.taptech.doufu.listener.PublicInterface;
import com.taptech.doufu.manager.NovelEditManager;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.bean.MineNovelBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.NovelDraftBean;
import com.taptech.doufu.bean.NovelDraftContentBean;
import com.taptech.doufu.bean.NovelDraftDesBean;
import com.taptech.doufu.bean.NovelEditModel;
import com.taptech.doufu.bean.NovelSectionBean;
import com.taptech.doufu.umeng.push.InAppMessageKey;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.TimeDateFunction;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.RecyclerViewAdapterAsListView;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.ui.viewholder.personalcenter.MessageViewHolderFactory;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.services.NovelCreateServices;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;
import com.taptech.doufu.ui.view.WaitDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by longsiyang on 15/10/27.
 */
public class NewNovelCreateListTosActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener
{

    public final static int RESULT_CHANGE_NOVEL = 33;
    public static final int NOVEL_CREATE = 2;

    static public final int REFRESH_REQUEST_CODE = 1001;
    static public final int REFRESH_RESULT_CODE = 1002;
    static public final int RESULT_DEL_NOVEL = 1003;
    static public final int RESULT_NOVEL_SET = 1004;


    // 数据
    private String novelId;
    private String novelName;
    private String icon;
    private MineNovelBean novelBean;
    // dataList
    List<MineAbstractBean> mDataList;
    List<MineAbstractBean> mDraftList;
    List<MineAbstractBean> mSectionList;

    private MessageViewHolderFactory viewHolderFactory;
    private TextView tvNovelTitle;
    private TextView tvHelp;
    private ImageView ivHelp;
    private LinearLayout llSetup;
    private LinearLayout mAddSectionBtn;
    private MyRecyclerView sectionListView;
    private RecyclerViewAdapterAsListView adapter;
    private WaitDialog dialog;

    // 控制标志
    private boolean hasMoreContent = false;
    private String last = "";
    private int httpRequestCount = 0;
    private String sectionOrder = "3";
    private HashMap<String,String> unSyncNovelIDMap;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshData(final EventBusRefreshData event) {
        if (event != null && EventBusRefreshData.tag.equals(event.getTag())) {
            NovelEditManager.getInstance().getNovelIdMap(novelId, new PublicInterface.OnHashMapResult() {
                @Override
                public void onResult(HashMap hashMap) {
                    unSyncNovelIDMap = hashMap;
                    if (event.isError()) {
                        updateList();
                        adapter.notifyDataSetChanged();
                    }else{
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                        loadRefreshData();
                    }
                }
            });

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_novel_create_list_tos);
        initData();
        initView();
        loadRefreshData();
        PushManager.getInstance().inAppMessage(this,InAppMessageKey.CHAPTER_LIST);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData()
    {
        mDataList = new ArrayList<>();
        mDraftList = new ArrayList<>();
        mSectionList = new ArrayList<>();
        // 获取小说id
        novelId = getIntent().getStringExtra(Constant.NOVEL_ID);
        novelName = getIntent().getStringExtra(Constant.NOVEL_NAME);
        NovelEditManager.getInstance().getNovelIdMap(novelId, new PublicInterface.OnHashMapResult() {
            @Override
            public void onResult(HashMap hashMap) {
                unSyncNovelIDMap = hashMap;
            }
        });
    }

    private void initView()
    {
        tvNovelTitle = (TextView) findViewById(R.id.activity_novel_create_list_title);
        tvNovelTitle.setText(novelName);

        viewHolderFactory = new MessageViewHolderFactory();
        sectionListView = (MyRecyclerView) findViewById(R.id.novel_section_listview);
        RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(1, RecyclerView.VERTICAL);
        sectionListView.setLayoutManager(layoutManager);
        adapter = new RecyclerViewAdapterAsListView(this, mDataList, handler);
        adapter.setFooterVisible(false);
        sectionListView.setAdapter(adapter);
        sectionListView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener()
        {
            @Override
            public void loadMore()
            {
                loadMoreData();
            }
        });
        mAddSectionBtn = (LinearLayout) findViewById(R.id.add_section_btn);
        mAddSectionBtn.setOnClickListener(this);
        llSetup = (LinearLayout) findViewById(R.id.llSetup);
        llSetup.setOnClickListener(this);
        tvHelp = (TextView) findViewById(R.id.tvHelp);
        tvHelp.setOnClickListener(this);
        ivHelp = (ImageView) findViewById(R.id.ivHelp);
        ivHelp.setOnClickListener(this);
        dialog = new WaitDialog(this, R.style.updateDialog);
        dialog.show();
    }

    private synchronized void loadRefreshData()
    {
        last = "";
        httpRequestCount += 2;
//        if (mDataList != null)
//        {
//            mDataList.clear();
//        }
//        adapter.notifyDataSetChanged();
        adapter.pullComplete(false);
        hasMoreContent = true;
        NovelCreateServices.getInstance().loadMyDrafts(this, novelId);
        HomeMainServices.getInstance().loadNovelSectionList(this, novelId, last, sectionOrder);
    }

    private synchronized void loadMoreData()
    {
        if (hasMoreContent && httpRequestCount == 0)
        {
            httpRequestCount++;
            HomeMainServices.getInstance().loadNovelSectionList(this, novelId, last, sectionOrder);
        }

    }

    ArrayList<String> mNovelDetailsId = new ArrayList<String>();

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {

        if (handleType == NovelCreateServices.HANDLE_TYPE_MY_DRAFTS)
        {
            if (response == null)
            {
                UIUtil.toastMessage(this, Constant.loadingFail);
                return;
            }
            try
            {
                JSONObject data = (JSONObject) response.getData();
                JSONArray jsonArray = null;
                jsonArray = data.getJSONArray("drafts");
                List<? extends MineAbstractBean> draftlist = viewHolderFactory.getDataBeanFromJSONArray(jsonArray);
                if (mDraftList != null)
                {
                    mDraftList.clear();
                    mDraftList.addAll(draftlist);
                }

                if (httpRequestCount > 0)
                {
                    httpRequestCount--;
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }

        }
        HttpUtil.setOnHandleHttpResponListener(this, handleType, response, new HttpUtil.HandleHttpResponListener()
        {
            @Override
            public void handleRespon(int handleType, JSONObject data)
            {
                switch (handleType)
                {
                    case HomeMainServices.HANDLE_TYPE_LOAD_SECTION_NOVEL:
                        try
                        {
                            JSONObject jsonObject = data.getJSONObject("topic");
                            JSONArray idsArray = data.getJSONArray("ids");
                            mNovelDetailsId.clear();
                            for (int i = 0; i < idsArray.length(); i++)
                            {
                                mNovelDetailsId.add(idsArray.getString(i));
                            }
                            adapter.setNovelIDs(mNovelDetailsId);

                            if (novelBean == null)
                            {
                                novelBean = new MineNovelBean();
                            }
                            novelBean.setJson2(jsonObject);
                            int preCollect = data.getInt("pre_collect_count");
                            novelBean.setPre_collect_count(preCollect);
                            if(novelBean.getUser() != null && !TextUtils.isEmpty(novelBean.getUser().getIcon())){
                                icon = novelBean.getUser().getIcon();
                            }

                            JSONArray jsonArray = data.getJSONArray("main");
                            List<? extends MineAbstractBean> sectionlist = viewHolderFactory.getDataBeanFromJSONArray(jsonArray);
                            if (data.has("last"))
                            {
                                // 如果是刷新后的数据

                                if (last.equals(""))
                                {
                                    if (mSectionList != null && mDataList != null)
                                    {
                                        mSectionList.clear();
                                        mDataList.clear();
                                    }
                                }

                                // 如果已经拉完
                                if (data.getString("last").equals(last))
                                {
                                    hasMoreContent = false;
                                } else
                                {

                                    hasMoreContent = true;
                                    mSectionList.addAll(sectionlist);
                                }


                            }
                            if (httpRequestCount > 0)
                            {
                                httpRequestCount--;
                            }
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
                        break;
                }
                if (httpRequestCount == 0)
                {
                    // 更新ui
                    if (dialog != null && dialog.isShowing())
                    {
                        dialog.cancel();
                    }
                    try {
                        updateList();
                        if (hasMoreContent) {
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.pullComplete(true);
                        }
                        last = data.getString("last");

                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    private void updateList() {
        mDataList.clear();
        List<NovelEditModel> localList = NovelEditManager.getInstance().getCreatedList(novelId);
        if (localList != null && localList.size() > 0) {
            for (int i = 0; i < localList.size(); i++) {
                NovelEditModel model = localList.get(i);
                NovelDraftBean item = new NovelDraftBean();
                item.setBackupUnSync(true);
                item.setId("-1");
                item.setObject_type("44");
                item.setStatus("1");
                item.setObject_id(model.getNovel_id());
                item.setType("18");
                item.setDbId(model.getId());
                item.setExtral_text(model.getAuthor_say());
                item.setCreated_at(TimeDateFunction.toDateTime(model.getCreated_at()*1000));
                item.setUpdated_at(TimeDateFunction.toDateTime(model.getCreated_at()*1000));

                NovelDraftContentBean contentBean = new NovelDraftContentBean();
                contentBean.setObject_id(model.getNovel_id());
                contentBean.setText(model.getContent());
                contentBean.setObject_type("18");
                item.setContent(contentBean);

                NovelDraftDesBean desBean = new NovelDraftDesBean();
                desBean.setArticle_title(model.getTitle());
                desBean.setObject_id(model.getNovel_id());
                desBean.setObject_type("18");
                item.setDescription(desBean);
                mDataList.add(item);
            }
        }
        if (mDraftList != null && mDraftList.size() > 0)
        {
            for (int i = 0; i < mDraftList.size(); i++) {
                if (mDraftList.get(i) instanceof NovelDraftBean){
                    NovelDraftBean novelDraftBean = (NovelDraftBean) mDraftList.get(i);
                    if (unSyncNovelIDMap != null && unSyncNovelIDMap.containsKey(novelDraftBean.getId())) {
                        novelDraftBean.setBackupUnSync(true);
                    }else{
                        novelDraftBean.setBackupUnSync(false);
                    }
                    mDataList.add(novelDraftBean);
                }else{
                    mDataList.add(mDraftList.get(i));
                }
            }
        }
        if (mSectionList != null && mSectionList.size() > 0) {
            for (int i = 0; i < mSectionList.size(); i++) {
                if (mSectionList.get(i) instanceof NovelSectionBean) {
                    NovelSectionBean bean = (NovelSectionBean) mSectionList.get(i);
                    if (unSyncNovelIDMap != null && unSyncNovelIDMap.containsKey(bean.getId())) {
                        bean.setBackupUnSync(true);
                    }else{
                        bean.setBackupUnSync(false);
                    }
                    mDataList.add(bean);
                }else{
                    mDataList.add(mSectionList.get(i));
                }
            }
        }
    }

    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent();
        switch (v.getId())
        {
            case R.id.add_section_btn:
                NovelCreateServices.enterNovelCreateContentTos(this, NOVEL_CREATE, null, novelId, novelId, null, mNovelDetailsId, icon);
                break;
            case R.id.tvHelp:
                intent.setClass(this, BrowseActivity.class);
                intent.putExtra("URL","https://api.douhuawenxue.com/journal/detail?id=833");
                startActivity(intent);
                break;
            case R.id.ivHelp:
                intent.setClass(this, BrowseActivity.class);
                intent.putExtra("URL","https://api.douhuawenxue.com/journal/detail?id=833");
                startActivity(intent);
                break;
            case R.id.llSetup:
                NovelCreateServices.enterNovelSetting(this, novelBean);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case REFRESH_REQUEST_CODE:
                if (resultCode == REFRESH_RESULT_CODE)
                {
                    if (dialog != null && !dialog.isShowing())
                    {
                        dialog.show();
                    }
                    loadRefreshData();
                } else if (resultCode == RESULT_DEL_NOVEL)
                {
                    setResult(100);
                    finish();
                }else if(resultCode == RESULT_NOVEL_SET){
                    novelBean = (MineNovelBean) data.getSerializableExtra(Constant.DATA);
                }
                break;

        }
    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if (msg.what == REFRESH_REQUEST_CODE)
            {
                if (dialog != null && !dialog.isShowing())
                {
                    dialog.show();
                }
                loadRefreshData();
            }
        }
    };

    public static void startActivity(Context context,String novelId, String novelName) {
        Intent intent = new Intent(context, NewNovelCreateListTosActivity.class);
        intent.putExtra(Constant.NOVEL_ID, novelId);
        intent.putExtra(Constant.NOVEL_NAME, novelName);
        context.startActivity(intent);
    }
}
